﻿using Android;
using Android.AccessibilityServices;
using Android.App;
using Android.Content;
using Android.Views.Accessibility;
using AnyTap.Models;
namespace AnyTap;

[Service(Enabled = true, Exported = true, Name = "com.byo.anytap.TapAccessibilityService", Label = "触摸捕获辅助服务", Permission = Manifest.Permission.BindAccessibilityService)]
[IntentFilter(["android.accessibilityservice.AccessibilityService"])]
[MetaData("android.accessibilityservice", Resource = "@xml/accessibility_config")]
public class TapAccessibilityService : AccessibilityService
{
	static long tick = 0;
	static TapAccessibilityService Instance = null;
	static readonly Android.Graphics.Path path = new();

	protected override void OnServiceConnected()
	{
		Instance = this;
		base.OnServiceConnected();
	}

	public override bool OnUnbind(Intent intent)
	{
		Instance = null;
		return base.OnUnbind(intent);
	}

	public override void OnAccessibilityEvent(AccessibilityEvent e)
	{ }

	public override void OnInterrupt()
	{ }

	public static bool Gesture(TapGesture arg)
	{
		if(Instance is null || !OperatingSystem.IsAndroidVersionAtLeast(24))
			return false;

		switch(arg.Type)
		{
		case GestureType.Click:
			path.Reset();
			tick = Environment.TickCount64;
			path.MoveTo((float)arg.X, (float)arg.Y);
			Thread.Sleep(10);
			return Instance.DispatchGesture(new GestureDescription.Builder().AddStroke(new GestureDescription.StrokeDescription(path, 0, Environment.TickCount64 - tick)).Build(), null, null);
		case GestureType.Move:
			for(int i = Environment.TickCount64 - tick > 500 ? 20 : 1; i >= 0; i--) //模拟长按
			{
				path.LineTo((float)(arg.X + i % 5), (float)(arg.Y - i % 7));
			}
			break;
		case GestureType.TouchDown:
			path.Reset();
			tick = Environment.TickCount64;
			path.MoveTo((float)arg.X, (float)arg.Y);
			break;
		case GestureType.TouchUp:
			return Instance.DispatchGesture(new GestureDescription.Builder().AddStroke(new GestureDescription.StrokeDescription(path, 0, Environment.TickCount64 - tick)).Build(), null, null);
		default:
			break;
		}

		return true;
	}
}
